/**
 * &copy; 2006 NewInstance.it
 */
package it.newinstance.util.servlet;




import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * @author Luigi R. Viggiano
 * @version $Id: JSMinFilter.java 157 2007-06-22 00:16:19Z luigi.viggiano $
 */
public class JSMinFilter extends HttpPatternFilter {

    @Override
    public void filter(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        String path = request.getRequestURI().substring(
                request.getContextPath().length());

        log("JSMinFilter: Filtering requested URI: " + path);
        HttpServletResponse responseWrapper = new HttpServletResponseWrapper(
                response) {
            ServletOutputStream outputStream = new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                    buffer.write(b);
                }
            };

            PrintWriter writer = new PrintWriter(outputStream);

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
                return outputStream;
            }

            @Override
            public PrintWriter getWriter() throws IOException {
                return writer;
            }

            @Override
            public void setContentLength(int length) {
                /*
                 * overriding with empty implementattion to avoid
                 * chain.doFilter() to set this to original file size
                 */
            }

            @Override
            public void flushBuffer() throws IOException {
                writer.flush();
            }
        };

        chain.doFilter(request, responseWrapper);
        responseWrapper.flushBuffer();

        InputStream in = new ByteArrayInputStream(buffer.toByteArray());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        JSMin jsmin = new JSMin(in, out);
        try {
            jsmin.jsmin();
            response.getWriter().write(out.toString());
        } catch (Exception e) {
            log("JSMinFilter: JSMin threw an exception", e);
            throw new ServletException(e);
        }
    }
}
